//
//  MTInviteInfoCell.swift
//  MT
//
//  Created by ooops on 2020/5/26.
//  Copyright © 2020 张强. All rights reserved.
//

//
//  MTFriendViewRequestVerifyCell.swift
//  MT
//
//  Created by ooops on 2020/5/6.
//  Copyright © 2020 张强. All rights reserved.
//

import UIKit
import MTCategory
import Result

protocol MTInviteInfoCellDelegate: NSObjectProtocol {
    /// 拒绝好友请求
    func rejectInvitation()
    /// 同意好友请求
    func confrimInvitation(userName: String)
}

class MTInviteInfoCell: UITableViewCell {
    
    /// MTProvider
    fileprivate lazy var taskProvider: MTProvider<MTCreateTaskAPI> = {
        return MTProvider<MTCreateTaskAPI>(plugins: [])
    }()
    
    var model: MTTaskInviteInfoSubModel? {
        didSet {
            userIconView.mtSetImage(model?.userHref, nil)
            userNickNameLabel.text = model?.nickname
            if let name = model?.name {
                msgTipLabel.text = "申请加入你发布的“\(name)”"
            }
            if model?.age != nil && model?.area != nil {
                descriptionLabel.text = "\(model?.age ?? 0)岁 | \(model?.area ?? "")"
            } else if model?.area == nil {
                descriptionLabel.text = "\(model?.age ?? 0)岁"
            } else {
                descriptionLabel.text = "\(model?.area ?? "")"
            }
            
            if let remark = model?.remark, remark.count > 0 {
                msgLabel.text = remark
            } else {
                msgLabel.text = "这家伙很懒, 什么都没留下"
            }
            
            communitButton.isHidden = true
            tagListView.snp.updateConstraints { (make) in
                make.height.equalTo(model?.tagList?.count ?? 0 > 0 ? 30 : 0)
            }
            tagListView.removeAllTags()
            tagListView.addTags(model?.tagList ?? [])
            if model?.roleType == 1 {
                if model?.joinStatus == 0 {
                    rejectButton.isHidden = false
                    acceptButton.isHidden = false
                    statusLabel.isHidden = true
                } else {
                    rejectButton.isHidden = true
                    acceptButton.isHidden = true
                    statusLabel.isHidden = false
                    statusLabel.text = model?.joinStatus == 1 ? "已拒绝" : "已接受"
                }
            }
        }
    }
    
    weak var delegate: MTInviteInfoCellDelegate?
    
    lazy var userIconView: UIImageView = {
        let imageV = UIImageView()
        imageV.layer.cornerRadius = 22
//        imageV.layer.borderWidth = 1
//        imageV.layer.borderColor = UIColor.black.cgColor
        imageV.layer.masksToBounds = true
        return imageV
    }()
    
    lazy var userNickNameLabel: UILabel = {
        let l = UILabel()
        l.font = PingFangSCSemiboldFont(14)
        l.textColor = UIColor.text.x1d1a1a
        //l.text = "帅气小伙子"
        return l
    }()
    
    lazy var descriptionLabel: UILabel = {
        let l = UILabel()
        l.font = PingFangSCMediumFont(12)
        l.textColor = UIColor.text.x1d1a1a
        //l.text = "21岁   西湖区    8km"
        return l
    }()
    
    lazy var msgTipLabel: UILabel = {
        let l = UILabel()
        l.font = PingFangSCMediumFont(12)
        l.textColor = UIColor.text.x9b9b9b
        l.text = "附加留言"
        return l
    }()
    
    lazy var msgLabelBgView: UIView = {
        let v = UIView()
        v.backgroundColor = UIColor(hex: 0xf6f6f6)
        v.layer.cornerRadius = 4
        return v
    }()
    
    lazy var msgLabel: UILabel = {
        let l = UILabel()
        l.font = PingFangSCMediumFont(12)
        l.textColor = UIColor.text.x1d1a1a
        //l.text = "f你点接收, 我点你的心"
        l.numberOfLines = 0
        l.preferredMaxLayoutWidth = ScreenWidth - 10 - 10 - 44 - 10
        l.lineBreakMode = .byWordWrapping
        return l
    }()
    
    lazy var rejectButton: UIButton = {
        let btn = UIButton(type: .custom)
        btn.setTitle("拒绝", for: .normal)
        btn.addTarget(self, action: #selector(rejectRequest), for: .touchUpInside)
        btn.setTitleColor(UIColor.text.x1d1a1a, for: .normal)
        btn.titleLabel?.font = PingFangSCRegularFont(14)
        return btn
    }()
    
    lazy var acceptButton: UIButton = {
        let btn = UIButton(type: .custom)
        btn.setTitle("接受", for: .normal)
        btn.addTarget(self, action: #selector(acceptRequest), for: .touchUpInside)
        btn.setTitleColor(UIColor(hex: 0x29282b), for: .normal)
        btn.titleLabel?.font = PingFangSCSemiboldFont(14)
        btn.backgroundColor = UIColor(hex: 0xffc000)
        return btn
    }()
    
    lazy var communitButton: UIButton = {
        let btn = UIButton(type: .custom)
        btn.setTitle("沟通群", for: .normal)
        btn.setImage(UIImage(named: "icon_right_gary"), for: .normal)
        btn.imageView?.tintColor = .blue
        btn.addTarget(self, action: #selector(commmunication), for: .touchUpInside)
        btn.setTitleColor(UIColor(hex: 0x29282b), for: .normal)
        btn.titleLabel?.font = PingFangSCMediumFont(14)
        btn.setTitleColor(UIColor.init(red: 66, green: 107, blue: 242), for: .normal)
        btn.isHidden = true
        return btn
    }()
    
    lazy var tagListView: TagListView = {
        let v = TagListView()
        v.tagSelectedBackgroundColor = UIColor(hex: 0x426bf2)
        v.tagHighlightedBackgroundColor = UIColor(hex: 0x426bf2)
        v.tagBackgroundColor = UIColor(hex: 0x426bf2)
        v.textFont = PingFangSCMediumFont(10)
        v.textColor = UIColor.white
        v.cornerRadius = 8
        v.paddingX = 12
        v.paddingY = 4
        v.marginX = 10
        v.marginY = 10
//        v.borderColor = UIColor.text.x9b9b9b
//        v.borderWidth = 1
        //v.shadowColor = UIColor.black
        //v.shadowOffset = CGSize(width: 1, height: 1)
        //v.addTags(["不迟到", "有才艺", "会剪辑", "粉丝多", "表演能力强", "资金实力厚"])
        v.alignment = .left
        return v
    }()
    
    lazy var statusLabel: UILabel = {
        let l = UILabel()
        l.font = PingFangSCRegularFont(14)
        l.textColor = UIColor.text.x9b9b9b
        l.textAlignment = .center
        l.isHidden = true
        return l
    }()
    
    lazy var giftIconView: UIImageView = {
        let imageV = UIImageView()
        imageV.layer.borderColor = UIColor.black.cgColor
        imageV.layer.borderWidth = 1
        return imageV
    }()
    
    lazy var giftsLabel: UILabel = {
        let l = UILabel()
        l.font = PingFangSCSemiboldFont(24)
        l.textColor = UIColor.text.x1d1a1a
        l.text = "33"
        return l
    }()
    
    @objc private func commmunication() {
        
    }
    
    lazy var lineView: UIView = {
        let v = UIView()
        v.backgroundColor = UIColor(hex: 0xf6f6f6)
        return v
    }()
    
    lazy var bottomLineView: UIView = {
        let v = UIView()
        v.backgroundColor = UIColor.init(red: 246, green: 246, blue: 246)
        return v
    }()
    
    class func reuseIdentity() -> String {
        return "MTInviteInfoCellID"
    }
    
    override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)
        setupUI()
        makeConstraint()
        self.selectionStyle = .none
    }
    
    private func setupUI() {
        contentView.addSubview(userIconView)
        contentView.addSubview(userNickNameLabel)
        contentView.addSubview(descriptionLabel)
        contentView.addSubview(msgLabelBgView)
        
        contentView.addSubview(tagListView)
        
        contentView.addSubview(msgTipLabel)
        msgLabelBgView.addSubview(msgLabel)
        contentView.addSubview(rejectButton)
        contentView.addSubview(acceptButton)
        contentView.addSubview(statusLabel)
        
        contentView.addSubview(lineView)
        contentView.addSubview(bottomLineView)
    }
    
    private func makeConstraint() {
        
        userIconView.snp.makeConstraints { (make) in
            make.top.left.equalToSuperview().offset(10)
            //make.size.equalTo(CGSize(width: 44, height: 44))
            make.width.equalTo(44)
            make.height.equalTo(44)
        }
        
        userNickNameLabel.snp.makeConstraints { (make) in
            make.left.equalTo(userIconView.snp.right).offset(10)
            make.bottom.equalTo(userIconView.snp.centerY).offset(-2)
        }
        
        descriptionLabel.snp.makeConstraints { (make) in
            make.left.equalTo(userNickNameLabel)
            make.top.equalTo(userIconView.snp.centerY).offset(2)
        }
        
        msgTipLabel.snp.makeConstraints { (make) in
            make.left.equalTo(userNickNameLabel)
            make.top.equalTo(userIconView.snp.bottom).offset(6)
        }
        
        msgLabelBgView.snp.makeConstraints { (make) in
            make.left.equalTo(userNickNameLabel)
            make.top.equalTo(msgTipLabel.snp.bottom).offset(2)
            //make.bottom.equalTo(rejectButton.snp.top).offset(-20)
            make.right.equalToSuperview().offset(-10)
        }
        
        tagListView.snp.makeConstraints { (make) in
            make.left.right.equalTo(msgLabelBgView)
            make.top.equalTo(msgLabelBgView.snp.bottom).offset(10)
            make.height.equalTo(30)
        }
        
        msgLabel.snp.makeConstraints { (make) in
            make.left.equalToSuperview().offset(10)
            make.top.equalToSuperview().offset(8)
            make.bottom.equalToSuperview().offset(-8)
            make.right.equalToSuperview().offset(-10)
        }
        
        rejectButton.snp.makeConstraints { (make) in
            make.left.equalToSuperview()
            make.height.equalTo(36)
            make.width.equalToSuperview().multipliedBy(0.5)
            make.centerY.equalTo(statusLabel)
        }
        
        acceptButton.snp.makeConstraints { (make) in
            make.right.equalToSuperview()
            make.height.equalTo(36)
            make.width.equalToSuperview().multipliedBy(0.5)
            make.centerY.equalTo(statusLabel)
        }
        
        statusLabel.snp.makeConstraints { (make) in
            make.left.right.equalToSuperview()
            make.bottom.equalTo(bottomLineView.snp.top)
            make.height.equalTo(36)
        }
        
        lineView.snp.makeConstraints { (make) in
            make.top.equalTo(tagListView.snp.bottom).offset(20)
            make.left.right.equalToSuperview()
            make.bottom.equalTo(statusLabel.snp.top)
            make.height.equalTo(2)
        }
        
        bottomLineView.snp.makeConstraints { (make) in
            make.left.right.bottom.equalToSuperview()
            make.height.equalTo(11)
        }
    }
    
    @objc private func rejectRequest() {
        guard let userName = model?.userName else { return }
        guard let id = model?.partyId else { return }
        let dic: [String  : Any] = ["partyId" : id, "userName" : userName, "type" : 1]
        MBProgressHUD_JChat.showLoading(self.viewController?.view)
        rejectButton.isUserInteractionEnabled = false
        MTCreateTaskTool.operateInvite(provider: taskProvider, parameters: dic, complete: { [weak self] (model) in
            guard let weakSelf = self else { return }
            DispatchQueue.main.async {
                weakSelf.rejectButton.isUserInteractionEnabled = true
                MBProgressHUD_JChat.dismiss(weakSelf.viewController?.view)
            }
            if model?.code == 200 {
                MBProgressHUD_JChat.dismiss(weakSelf.viewController?.view)
                weakSelf.model?.joinStatus = 1
                self?.delegate?.rejectInvitation()
            }
        }) { (_) in
            DispatchQueue.main.async {
                self.rejectButton.isUserInteractionEnabled = true
                MBProgressHUD_JChat.dismiss(self.viewController?.view)
            }
        }
    }
    
    @objc private func acceptRequest() {
        guard let userName = model?.userName else { return }
        guard let id = model?.partyId else { return }
        MBProgressHUD_JChat.showLoading(self.viewController?.view)
        acceptButton.isUserInteractionEnabled = false
        let dic: [String  : Any] = ["partyId" : id, "userName" : userName, "type" : 2]
        MTCreateTaskTool.operateInvite(provider: taskProvider, parameters: dic, complete: { [weak self] (model) in
            guard let weakSelf = self else { return }
            DispatchQueue.main.async {
                weakSelf.acceptButton.isUserInteractionEnabled = true
                MBProgressHUD_JChat.dismiss(weakSelf.viewController?.view)
            }
            if model?.code == 200 {
                weakSelf.model?.joinStatus = 2
                self?.delegate?.confrimInvitation(userName: userName)
            }
            if model?.code == 400, let msg = model?.message {
                MBProgressHUD_JChat.show(text: msg, view: weakSelf.viewController?.view, 1)
                DispatchQueue.main.after(1) {
                    weakSelf.rejectRequest()
                }
            }
        }) { (_) in
            DispatchQueue.main.async {
                self.acceptButton.isUserInteractionEnabled = true
                MBProgressHUD_JChat.dismiss(self.viewController?.view)
            }
        }
    }
    
    required init?(coder: NSCoder) {
        super.init(coder: coder)
    }

    override func awakeFromNib() {
        super.awakeFromNib()
        // Initialization code
    }

    override func setSelected(_ selected: Bool, animated: Bool) {
        super.setSelected(selected, animated: animated)

        // Configure the view for the selected state
    }

}


